package com.duff.download.demo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.duff.download.okdownload.LiteDownload;
import com.duff.download.okdownload.OkDownload;
import com.duff.download.okdownload.interfaces.DownloadTaskCompleteListener;
import com.duff.download.okdownload.interfaces.LiteDownloadListener;
import com.duff.download.okdownload.interfaces.OnDownloadListener;
import com.duff.download.okdownload.utils.Utils;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private Button bt_list_download;
    private Button bt_sync_download;
    private Button bt_download, bt_cancel;
    private Button bt_lite_download;
    private Button bt_batch_download;
    private EditText et_url;

    private OkDownload mOkDownload;

    private String DOWNLOAD_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa/";

    private final String[] urls = new String[]{
            "http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=9909ddc1b91c8701c2bbbaa54f16f45a/a08b87d6277f9e2fb0727e2d1530e924b899f354.jpg",
            "http://f3.market.xiaomi.com/download/AppStore/08c674eee0f857ed80f0efa9158a6cb021c42957b/com.imibaby.client.apk",
            "http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=ae4e87268d94a4c21e2eef68669d71a0/7c1ed21b0ef41bd5d5a88edd5bda81cb39db3d1b.jpg"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_download = (Button) findViewById(R.id.bt_download);
        bt_download.setOnClickListener(this);
        bt_sync_download = (Button) findViewById(R.id.bt_sync_download);
        bt_sync_download.setOnClickListener(this);
        bt_cancel = (Button) findViewById(R.id.bt_cancel);
        bt_cancel.setOnClickListener(this);
        bt_lite_download = (Button) findViewById(R.id.bt_lite_download);
        bt_lite_download.setOnClickListener(this);
        bt_batch_download = (Button) findViewById(R.id.bt_batch_download);
        bt_batch_download.setOnClickListener(this);

        bt_list_download = (Button) findViewById(R.id.bt_list_download);
        bt_list_download.setOnClickListener(this);

        et_url = (EditText) findViewById(R.id.et_url);

        checkPermission();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_download:
                download();
                break;

            case R.id.bt_cancel:
                cancel();
                break;

            case R.id.bt_lite_download:
                liteDownload();
                break;

            case R.id.bt_batch_download:
                batchDownload();
                break;

            case R.id.bt_list_download:
                startActivity(new Intent(MainActivity.this, ListDownloadActivity.class));
                break;

            case R.id.bt_sync_download:
                startActivity(new Intent(MainActivity.this, SyncDownloadActivity.class));
                break;

            default:
                break;
        }
    }

    private void download() {
        String url = et_url.getText() != null ? et_url.getText().toString() : "";
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(this, "请输入下载地址", Toast.LENGTH_SHORT).show();
            return;
        }

//        OkDownload okDownload = new OkDownload.Builder()
//                .url(url)
//                .tag("test")
//                .path(DOWNLOAD_DIR + Utils.getFileName(url))
//                .build();
//
//        okDownload.download(new OnDownloadListener() {
//            @Override
//            public void onStart(String url) {
//                Log.d(TAG, "onStart ... ");
//            }
//
//            @Override
//            public void onError(String url, Exception e) {
//                Log.d(TAG, "onError ... " + e.getMessage());
//            }
//
//            @Override
//            public void onProgress(String url, long downloadedBytes, long totalBytes, File file) {
//                Log.d(TAG, "onProgress ... " + downloadedBytes + "/" + totalBytes);
//            }
//
//            @Override
//            public void onSuccess(String url, File file) {
//                Log.d(TAG, "onSuccess ... ");
//            }
//        });

        OkDownload.download(url, DOWNLOAD_DIR + Utils.getFileName(url), new OnDownloadListener() {
            @Override
            public void onStart(String url) {
                Log.d(TAG, "onStart ... ");
            }

            @Override
            public void onError(String url, Exception e) {
                Log.d(TAG, "onError ... " + e.getMessage());
            }

            @Override
            public void onProgress(String url, long downloadedBytes, long totalBytes, File file) {
                Log.d(TAG, "onProgress ... ");
            }

            @Override
            public void onSuccess(String url, File file) {
                Log.d(TAG, "onSuccess ... ");
            }
        });


    }

    private void cancel() {
        if (mOkDownload != null) {
            mOkDownload.cancel();
        }
    }

    private void liteDownload() {
        String url =  "http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=9909ddc1b91c8701c2bbbaa54f16f45a/a08b87d6277f9e2fb0727e2d1530e924b899f354.jpg";
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(this, "请输入下载地址", Toast.LENGTH_SHORT).show();
            return;
        }

        LiteDownload.download(url, DOWNLOAD_DIR + Utils.getFileName(url), new LiteDownloadListener() {
            @Override
            public void onError(Exception e) {
                Toast.makeText(MainActivity.this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(File file) {
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void batchDownload() {
        String[] paths = new String[urls.length];
        for (int i = 0; i < urls.length; i++) {
            String url = urls[i];
            String fileName = Utils.getFileName(url);
            String filePath = DOWNLOAD_DIR + fileName;
            paths[i] = filePath;
        }

        LiteDownload.download(true, urls, paths, new DownloadTaskCompleteListener() {
            @Override
            public void onComplete() {
                Toast.makeText(MainActivity.this, "All task download", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "已经拒绝了该权限！！！", Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }

        } else {
//            Toast.makeText(this, "已经申请了该权限！！！", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Toast.makeText(this, "申请权限成功！！！", Toast.LENGTH_SHORT).show();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "申请权限失败！！！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


}
